package com.cdb.configuration;

import javax.sql.DataSource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DataSourceConfig {

    @Value("${spring.datasource.local.url}")
    private String localJdbcUrl;

    @Value("${spring.datasource.ali.url}")
    private String aliJdbcUrl;

    @Bean(name = "primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.local")
    public DataSource primaryDataSource() {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(localJdbcUrl);
        return hikariDataSource;
    }

    @Bean(name = "primaryJdbcTemplate")
    @Primary
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "aliDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ali")
    public DataSource aliDataSource() {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(aliJdbcUrl);
        return hikariDataSource;
    }

    @Bean(name = "aliJdbcTemplate")
    public JdbcTemplate aliJdbcTemplate(@Qualifier("aliDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}